#include "Engine.h"

Slider::Slider()
	{
		id = (DWORD)this;
		bStatic = false;
		bVisible = true;
		bEnabled = true;
		bPressed = false;
		bVertical = true;

		fMin=0; fMax=100; fVal=50;
		sprSlider = 0;

		PositionChanged = new Event();
	}

int Slider::GetMaxValue() 
{
	return fMax;
}

float Slider::GetRatioValue()
{
	return (float)fVal / fMax;
}

void Slider::SetSliderSprite(const char* texture, float x, float y, float w, float h)
{
	HTEXTURE tex = Engine::GetSingleton()->GetResourceManager()->GetTexture(texture);
	sprSlider = new hgeSprite(tex, x, y, w, h);
	sl_w = w;
	sl_h = h;
}

void Slider::SetMaxValue(float value)
{
	fMax = value;
}

void Slider::SetVertical(bool v)
{
	bVertical = v;
}

void Slider::SetPosition(float x, float y, float w, float h)
{
	rect.x1 = x;
	rect.x2 = x + w;
	rect.y1 = y;
	rect.y2 = y + h;
}

Slider::~Slider()
{
	if(sprSlider) delete sprSlider;
}

void		Slider::SetMode(float _fMin, float _fMax, int _mode) 
{ 
	fMin=_fMin; fMax=_fMax; mode=_mode; 
}

float		Slider::GetValue() const 
{ 
	return fVal; 
}

void Slider::SetValue(float _fVal)
{
	if(_fVal<fMin) fVal=fMin;
	else if(_fVal>fMax) fVal=fMax;
	else fVal=_fVal;
}

void Slider::Render()
{
	float xx, yy;
	float x1,y1,x2,y2;

	xx=rect.x1+(rect.x2-rect.x1 - sprSlider->GetWidth())*(fVal-fMin)/(fMax-fMin) + sprSlider->GetWidth() / 2.0f;
	yy=rect.y1+(rect.y2-rect.y1 - sprSlider->GetHeight())*(fVal-fMin)/(fMax-fMin) + sprSlider->GetHeight() / 2.0f;
		
	if(bVertical)
		switch(mode)
		{
			case HGESLIDER_BAR: x1=rect.x1; y1=rect.y1; x2=rect.x2; y2=yy; break;
			case HGESLIDER_BARRELATIVE: x1=rect.x1; y1=(rect.y1+rect.y2)/2; x2=rect.x2; y2=yy; break;
			case HGESLIDER_SLIDER: x1=(rect.x1+rect.x2-sl_w)/2; y1=yy-sl_h/2; x2=(rect.x1+rect.x2+sl_w)/2; y2=yy+sl_h/2; break;
		}
	else
		switch(mode)
		{
			case HGESLIDER_BAR: x1=rect.x1; y1=rect.y1; x2=xx; y2=rect.y2; break;
			case HGESLIDER_BARRELATIVE: x1=(rect.x1+rect.x2)/2; y1=rect.y1; x2=xx; y2=rect.y2; break;
			case HGESLIDER_SLIDER: x1=xx-sl_w/2; y1=(rect.y1+rect.y2-sl_h)/2; x2=xx+sl_w/2; y2=(rect.y1+rect.y2+sl_h)/2; break;
		}

	sprSlider->RenderStretch(x1, y1, x2, y2);
}

bool Slider::MouseLButton(bool bDown)
{
	bPressed=bDown;
	return false;
}

bool Slider::MouseMove(float x, float y)
{
	if(bPressed)
	{
		if(bVertical)
		{
			if(y>rect.y2-rect.y1) y=rect.y2-rect.y1;
			if(y<0) y=0;
			fVal=fMin+(fMax-fMin)*y/(rect.y2-rect.y1);
		}
		else
		{
			if(x>rect.x2-rect.x1) x=rect.x2-rect.x1;
			if(x<0) x=0;
			fVal=fMin+(fMax-fMin)*x/(rect.x2-rect.x1);
		}

		PositionChanged->Invoke((void*)this);
		return true;
	}

	return false;
}